/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.ui.activities.LoginActivity;
import utsc.apps.utschedule.ui.activities.TimetableArchiveActivity;
import utsc.apps.utschedule.util.AppUtils;
import utsc.apps.utschedule.util.database.DatabaseHelper;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.widget.Toast;

/**
 * The stock version of the setting preference fragment. This is recommended on
 * API level 11+.
 * 
 * @author Wenbin
 * 
 */
public class StockSettingFragment extends PreferenceFragment implements OnClickListener{
	private File[] _backups;
	private AlertDialog _restoreDialog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
	}
	
	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		String key=preference.getKey();
		
		//detect the option item that was clicked
		//handle the action accordingly
		if (key.equals("search_setting")) {
			Intent searchSettingIntent=new Intent(SearchManager.INTENT_ACTION_SEARCH_SETTINGS);
			startActivity(searchSettingIntent);
		}else if (key.equals("backup")) {
			DatabaseHelper.backupDb(getActivity());
		}else if (key.equals("restore")) {
			_backups=getBackups();
			if (_backups!=null&& _backups.length>0) {
				int fileSize=_backups.length;
				String[] fileNames=new String[fileSize];
				
				for (int i = 0; i < fileSize; i++) {
					fileNames[i]=_backups[i].getName();
				}
				_restoreDialog=new AlertDialog.Builder(getActivity()).setTitle("Select a backup").setItems(fileNames, this).create();
				_restoreDialog.show();
			}
		}else if (key.equals("user_login")) {
			Intent setLoginIntent=new Intent(getActivity(), LoginActivity.class);
			setLoginIntent.putExtra("setLogin", true);
			startActivity(setLoginIntent);
		}else if (key.equals("clear_login")) {
			AppUtils.deleteLoginPreferences(getActivity());
			Toast.makeText(getActivity(), "Login setting is cleared.", Toast.LENGTH_LONG).show();
		}else if (key.equals("clear_backup")){
			try {
				clearBackups();
				Toast.makeText(getActivity(), "All backups have been cleared!", Toast.LENGTH_LONG).show();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else if (key.equals("archive")) {
			Intent timetableArchiveIntent=new Intent(getActivity(), TimetableArchiveActivity.class);
			startActivity(timetableArchiveIntent);
		}
		return true;
	}
	
	@Override
	public void onStop() {
		if (_restoreDialog!=null) {
			if (_restoreDialog.isShowing()) {
				_restoreDialog.dismiss();
			}
		}
		super.onStop();
	}
	
	private File[] getBackups (){
		File backup=new File(Environment.getExternalStorageDirectory(),"/UTSChedule");
		if (backup.isDirectory()) {
			return backup.listFiles(new FilenameFilter() {
				
				@Override
				public boolean accept(File dir, String filename) {
					if (filename.contains("UTSChedule_")) {
						return true;
					}
					return false;
				}
			});
		}
		return null;
	}
	
	private void clearBackups() throws IOException{
		File backup=new File(Environment.getExternalStorageDirectory(),"/UTSChedule");
		if (backup.isDirectory()) {
			File[] backups= backup.listFiles(new FilenameFilter() {
				
				@Override
				public boolean accept(File dir, String filename) {
					if (filename.contains("UTSChedule_")) {
						return true;
					}
					return false;
				}
			});
			
			if (backups!=null) {
				for (File file : backups) {
					if(!file.delete())
						throw new IOException("Failed to delete File.");
				}
			}
		}
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		File selectedBackup=_backups[which];
		DatabaseHelper.restoreDb(selectedBackup.getPath(), getActivity());
	}
	
	
}
